package com.rongmai.web.utils;

import com.rongmai.db.model.User;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
public class UserUtils {

    public static final String currentUser = "currentUser";

    public static User getCurrentUser(HttpServletRequest request) {
        try {
            HttpSession session = request.getSession();
            User user = (User) session.getAttribute(currentUser);
            return user;
        } catch (Exception e) {
            log.error("获取当前用户异常", e);
        }
        return null;
    }

    public static String getCurrentUserName(HttpServletRequest request) {
        User user = getCurrentUser(request);
        if (user == null) return "";
        return user.getName();
    }

    public static void setCurrentUser(HttpServletRequest request, User user) {
        try {
            if (user == null) return;
            HttpSession session = request.getSession();
            session.setAttribute(UserUtils.currentUser, user);
        } catch (Exception e) {
            log.error("设置当前用户异常", e);
        }
    }
}
